const currentDate = new Date();
let selectedDate = currentDate;
let tasks = [];

function renderCalendar() {
    const currentDateString = selectedDate.toLocaleString('default', { month: 'long', year: 'numeric' });
    document.getElementById('currentMonth').innerText = currentDateString;

    const firstDayOfMonth = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), 1);
    const firstDayOfWeek = firstDayOfMonth.getDay();

    const daysInMonth = new Date(selectedDate.getFullYear(), selectedDate.getMonth() + 1, 0).getDate();

    const cells = document.querySelector('.cells');
    cells.innerHTML = '';

    for (let i = 0; i < firstDayOfWeek; i++) {
        const cell = document.createElement('div');
        cells.appendChild(cell);
    }

    for (let i = 1; i <= daysInMonth; i++) {
        const cell = document.createElement('div');
        cell.innerText = i;
        cell.addEventListener('click', () => {
            openTaskModal(i);
        });

        if (areDatesEqual(currentDate, selectedDate) && i === currentDate.getDate()) {
            cell.classList.add('highlight');
        }

        cells.appendChild(cell);
  }
    
}

function areDatesEqual(date1, date2) {
    return date1.getDate() === date2.getDate() && date1.getMonth() === date2.getMonth() && date1.getFullYear() === date2.getFullYear();
}

function prevMonth() {
    selectedDate.setMonth(selectedDate.getMonth() - 1);
    renderCalendar();
}

function nextMonth() {
    selectedDate.setMonth(selectedDate.getMonth() + 1);
    renderCalendar();
}

function addTask() {
    const taskInput = document.getElementById('taskInput');
    const taskText = taskInput.value;

    if (taskText.trim() === '') {
        return;
    }

    const task = {
        date: selectedDate.getDate(),
        month: selectedDate.getMonth() + 1,
        year: selectedDate.getFullYear(),
        text: taskText
    };

    tasks.push(task);
    taskInput.value = '';
    renderTaskList();
}

function renderTaskList() {
    const taskList = document.getElementById('taskList');
    taskList.innerHTML = '';

    for (let i = 0; i < tasks.length; i++) {
        const task = tasks[i];

        if (task.date === selectedDate.getDate() && task.month === selectedDate.getMonth() + 1 && task.year === selectedDate.getFullYear()) {
            const listItem = document.createElement('li');
            listItem.innerText = task.text;
            taskList.appendChild(listItem);
        }
    }
}

function openTaskModal(day) {
    selectedDate.setDate(day);
    renderTaskList();
}

renderCalendar();


